<template>
  <div class="qrcode-container">
    <div class="qrcode-box">
      <qrcode-vue 
        :value="qrcodeUrl" 
        :size="200" 
        level="M" 
        render-as="svg"
      />
    </div>
    <div class="qrcode-tip">
      <p>请使用手机APP扫码登录</p>
      <el-button type="primary" link @click="refreshQrCode">
        刷新二维码
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import QrcodeVue from 'qrcode.vue'
import { getQrCode, checkQrCodeStatus } from '@/api/login'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { useRouter } from 'vue-router'

const qrcodeUrl = ref('')
let timer = null

const router = useRouter()
const userStore = useUserStore()

onMounted(() => {
  getQrCodeData()
  startPolling()
})

onUnmounted(() => {
  stopPolling()
})

const getQrCodeData = async () => {
  try {
    const res = await getQrCode()
    qrcodeUrl.value = res.data.qrCodeUrl
  } catch (error) {
    ElMessage.error('获取二维码失败')
  }
}

const refreshQrCode = () => {
  getQrCodeData()
}

const startPolling = () => {
  timer = setInterval(async () => {
    try {
      const res = await checkQrCodeStatus()
      if (res.data.scanned) {
        stopPolling()
        await userStore.setLoginState(res.data)
        ElMessage.success('登录成功')
        router.push('/')
      }
    } catch (error) {
      console.error('检查扫码状态失败:', error)
    }
  }, 2000)
}

const stopPolling = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}
</script>

<style scoped>
.qrcode-container {
  padding: 30px 0;
  text-align: center;
}

.qrcode-box {
  display: inline-block;
  padding: 16px;
  background: #fff;
  border: 1px solid #eee;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.qrcode-tip {
  margin-top: 24px;
  color: #666;
}

.qrcode-tip p {
  margin-bottom: 12px;
  font-size: 14px;
}

:deep(.el-button--link) {
  font-size: 14px;
}
</style> 